from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from note.models import Note


# Create your views here.
def login_check(a_func):
    def wrapped_func(request, *args, **kwargs):
        if 'uid' not in request.session or 'uname' not in request.session:
            return HttpResponseRedirect('/user/login')
        return a_func(request, *args, **kwargs)
    return wrapped_func


@login_check
def list_view(request):
    uname=request.session['uname']
    uid=request.session['uid']
    notes=Note.objects.filter(user_id=uid)
    return render(request,'note/list_note.html',locals())


@login_check
def add_view(request):
    if request.method=='GET':
        return render(request,'note/add_note.html')
    elif request.method=='POST':
        title=request.POST.get('title')
        content=request.POST.get('content')
        uid=request.session['uid']
        if not title or not content:
            return HttpResponse('标题或内容不能为空!,<a href="/note/add">返回</a>')
        try:
            Note.objects.create(title=title,content=content,user_id=uid)
        except:
            return HttpResponse('添加笔记失败!,<a href="/note/add">返回</a>')
        return HttpResponseRedirect('/note/')

@login_check
def mod_view(request,id):
    if request.method=='GET':
        note=Note.objects.get(id=id)
        return render(request,'note/mod_note.html',locals())
    elif request.method=='POST':
        title=request.POST.get('title')
        content=request.POST.get('content')
        if not title or not content:
            return HttpResponse('标题或内容不能为空,<a href="/note/add">返回</a>')
        note=Note.objects.get(id=id)
        note.title=title
        note.content=content
        note.save()
        return HttpResponseRedirect('/note/')


@login_check
def del_view(request,id):
    note=Note.objects.get(id=id)
    note.delete()
    return HttpResponseRedirect('/note/')
